﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Swift {
    /// <summary>
    /// 用于物品ID
    /// 分为正式使用和临时2种
    /// 正式使用是尽可能节约
    /// 临时使用是随便整
    /// </summary>
    public static class UniqueID {
        // 服务器ID
        public static UInt64 ServerID = 1;
        static UInt64 lastSecond = 0;
        static UInt64 index = 0;

        // 1. 服务器时间总是准确
        // 2. 服务器不会在1秒内重启，就OK
        // 这2个条件满足，UID就不会有问题
        public static string Create() {
            UInt64 nowSecond = (UInt64) DateTime.Now.Subtract (new DateTime (2017, 1, 1)).TotalSeconds;
            if(lastSecond == nowSecond) {
                // 如果上一次生成ID时的秒数和这次一样，就加索引
                index++;
            } else {
                // 秒数变了则重置索引
                lastSecond = nowSecond;
                index = 0;
            }

            string uid = string.Format ("{0}_{1}_{2}", ServerID, nowSecond, index);
            return uid;
        }
    }
}
